/**
 * 通用输送线 - 被输送物.
 */
export default {
  start: function() {
    this.log = HaloEngine.Utils.Logger.getLogger('Ext-Script');
  },
  onParameterUpdate: function (self, ctx, key, value) {
    const FORCE = 'pForce';
    if (key === FORCE) {

      // 计算应力合力
      const velocity = Object.values(value).reduce((final, curr) => {
        // 空值过滤
        if (curr == null) {
          return final;
        }
        // 异常值过滤
        if (curr.vector == null) {
          this.log.warn('Illegal pForce value: ', value);
          return final;
        }

        // 优先级检测
        if (curr.priority > final.priority) {
          return curr;
        }
        if (curr.priority < final.priority) {
          return final;
        }

        // 优先级相同, 进行应力合并
        return {
          vector: {
            x: this.synergy(final.vector.x, curr.vector.x),
            y: this.synergy(final.vector.y, curr.vector.y),
            z: this.synergy(final.vector.z, curr.vector.z),
          },
          priority: Math.max(final.priority, curr.priority),
        };
      }, {
        vector: {
          x: 0,
          y: 0,
          z: 0,
        },
        priority: 0,
      }).vector;

      // 如果存在刚体系统, 则更新刚体系统
      if (self.hasComponent('RigidbodyComponent')) {
        self.getComponent('RigidbodyComponent').velocity = velocity;
      }
    }
  },
  synergy: function (a, b) {
    const v1 = parseFloat(a) || 0;
    const v2 = parseFloat(b) || 0;

    // 同 0 应力, 直接返回 0
    if (v1 === 0 && v2 === 0) {
      return 0;
    }

    // 同向应力, 取绝对值最大值
    if (v1 * v2 > 0) {
      /*
       * 应力(F) = 方向(D) * Max(|A|, |B|)
       * 方向(D) = |A| / A
       */
      return (Math.abs(v1) / v1) * Math.max(Math.abs(v1), Math.abs(v2));
    }

    // 非同向应力, 取和力
    return v1 + v2;
  },
}